package xyz.luhui1hao.sell.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.luhui1hao.sell.dto.OrderDTO;
import xyz.luhui1hao.sell.exception.SellException;
import xyz.luhui1hao.sell.service.BuyerService;
import xyz.luhui1hao.sell.service.OrderService;

import static xyz.luhui1hao.sell.enums.ResultEnum.ORDER_NOT_EXIST;
import static xyz.luhui1hao.sell.enums.ResultEnum.ORDER_OWNER_ERROR;

/**
 * @ClassName BuyerServiceImpl
 * @Description TODO
 * @Author luhui1hao
 * @Date 2018/9/4 下午4:50
 * @Version 1.0
 */
@Slf4j
@Service
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancel(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if(orderDTO == null){
            log.error("【取消订单】订单不存在， orderId = {}", orderId);
            throw new SellException(ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId){
        OrderDTO orderDTO = orderService.findOne(orderId);
        if(orderDTO == null){
            return null;
        }
        //判断是否是自己的订单
        if(!orderDTO.getBuyerOpenId().equals(openid)){
            log.error("【查询订单】订单的openid不一致， openid = {}， orderId = {}", openid, orderId);
            throw new SellException(ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
